package cn.itcast.bos.service.system.Imp;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.dao.system.MenuDao;
import cn.itcast.bos.dao.system.PermissionDao;
import cn.itcast.bos.dao.system.RoleDao;
import cn.itcast.bos.domain.system.Menu;
import cn.itcast.bos.domain.system.Permission;
import cn.itcast.bos.domain.system.Role;
import cn.itcast.bos.domain.system.User;
import cn.itcast.bos.service.system.RoleService;

@Service
@Transactional
public class RoleServiceImp implements RoleService {

	@Autowired
	private RoleDao roledao;
	@Autowired
	private PermissionDao permissionDao;
	@Autowired
	private MenuDao menuDao;

	@Override
	public List<Role> findByUser(User user) {

		return roledao.findByUser(user.getId());
	}

	@Override
	public List<Role> finAll() {
		return roledao.findAll();
	}

	@Override
	public void save(Role model, String menuIds, String[] permissionIds) {
		roledao.save(model);
		//关联权限
		if (StringUtils.isAnyBlank(permissionIds)) {
			for (String permissionId : permissionIds) {
				Permission permission = permissionDao.findOne(Integer.parseInt(permissionId));
				model.getPermissions().add(permission);
			}

		}
		//关联菜单
		if (StringUtils.isAnyBlank(menuIds)) {
			   String[] ids = menuIds.split(",");
			for (String id : ids) {
				Menu menu = menuDao.findOne(Integer.parseInt(id));
				model.getMenus().add(menu);
			}
		}

	}

}
